package org.wsff.tools.state.core;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * SimpleStateTransferProvider
 * @author ryan
 * @version Id: SimpleStateTransferProvider.java, v 0.1 2022-03-28 18:11 ryan Exp $$
 */
public abstract class AbstractStateTransferProvider implements StateTransferProvider {

    protected static Map<String, StateTransfer> TRANSFERS_CACHE = new ConcurrentHashMap<>();

    /**
     * get state transfer
     *
     * @param from form state
     * @param to to state
     * @return state transfer
     */
    @Override
    public StateTransfer get(State from, State to) {
        return TRANSFERS_CACHE.get(TransferKey.create(from.id(), to.id()));
    }

    /**
     * init when the container is started
     */
    @Override
    public void init() {
        List<StateTransfer> transfers = getAllStateTransfers();
        Map<String, StateTransfer> stateTransfers = new ConcurrentHashMap<>();
        for (StateTransfer transfer : transfers) {
            stateTransfers.put(TransferKey.create(transfer.from(), transfer.to()), transfer);
        }
        TRANSFERS_CACHE = stateTransfers;
    }

    /**
     * get all state transfers
     * 
     * @return state transfers
     */
    protected abstract List<StateTransfer> getAllStateTransfers();

    /**
     * destroy when the container is stopped
     */
    @Override
    public void destroy() {

    }

    public static class TransferKey {

        private static final String SPLIT = "_$_";

        public static String create(String from, String to) {
            return from + SPLIT + to;
        }
    }
}
